﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Common
{
    public class TokenHelp
    {
        //填写自己微信的秘钥
        private static string appId = "wxe799d0444512ab48";
        private static string appSecret = "9f96d9ce3a5ce7d50b791e27342dcb39";

        private static DateTime GetAccessToken_Time;
        /// <summary>
        /// 过期时间为7200秒
        /// </summary>
        private static int Expires_Period = 7200;
        /// <summary>
        /// 
        /// </summary>
        private static string mAccessToken;
        /// <summary>
        /// 
        /// </summary>
        public static string AccessToken
        {
            get
            {
                //如果为空，需要重新获取
                if (string.IsNullOrEmpty(mAccessToken))
                { 
                    //获取
                    mAccessToken = GetAccessToken(appId, appSecret);
                }
                return mAccessToken;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        private static string GetAccessToken(string appId, string appSecret)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret);
            string result = HttpUtility.GetData(url); 
            XDocument doc = ParseJsonToXML(result, "root");
            XElement root = doc.Root;
            if (root != null)
            {
                XElement access_token = root.Element("access_token");
                if (access_token != null)
                {
                    GetAccessToken_Time = DateTime.Now;
                    if (root.Element("expires_in") != null)
                    {
                        Expires_Period = int.Parse(root.Element("expires_in").Value);
                    }
                    return access_token.Value;
                }
                else
                {
                    GetAccessToken_Time = DateTime.MinValue;
                }
            }
            return null;
        }
        /// <summary>
        /// 判断Access_token是否过期
        /// </summary>
        /// <returns>bool</returns>
        private static bool HasExpired()
        {
            if (GetAccessToken_Time != null)
            {
                //过期时间，允许有一定的误差，一分钟。获取时间消耗
                if (DateTime.Now > GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-110))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 将Json转化为XML
        /// </summary>
        /// <param name="json"></param>
        /// <param name="rootName"></param>
        /// <returns></returns>
        public static XDocument ParseJsonToXML(string json, string rootName)
        {
            return JsonConvert.DeserializeXNode(json, rootName);
        }


        /// <summary>
        /// 执行菜单请求
        /// </summary>
        /// <param name="url">微信提供的自定义菜单接口地址</param>
        /// <param name="postData">实现自定义菜单的Json字符串</param>
        public static string PostMenuData(string url, string postData)
        {
            string err = string.Empty;
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                 err = content;
            }
            catch (Exception)
            {
                 err = "菜单生成失败";
            }
            return err;
        }

        //创建微信菜单JSON字符串
        public static string GetWXMenuStr()
        {
            string weixin1 = "";
            weixin1 += "{\n";
            weixin1 += "\"button\":[\n";
            weixin1 += "{\n";
            // weixin1 += "\"type\":\"click\",\n";
            //第一个菜单
            weixin1 += "\"type\":\"view\",\n";
            weixin1 += "\"name\":\"内部办公\",\n";
            weixin1 += "\"url\":\"http://wx.chinanettj.com/\"\n";
            weixin1 += "},\n";
            //第二个菜单
            weixin1 += "{\n";
            weixin1 += "\"type\":\"view\",\n";
            weixin1 += "\"name\":\"金废一期\",\n"; 
            weixin1 += "\"url\":\"http://wx.chinanettj.com/\"\n";
            weixin1 += "}\n";
            weixin1 += "]\n";
            weixin1 += "}\n";
            return weixin1;
        }
    }
}
